﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SocketClient
{
    public partial class frmMain : Form
    {
        Socket socketClient;
        Thread thread;
        bool isAlive = false;
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnLink_Click(object sender, EventArgs e)
        {
            IPAddress ipAddress = IPAddress.Parse(txtIP.Text.Trim());
            int port = int.Parse(txtPort.Text.Trim());
            EndPoint endPoint = new IPEndPoint(ipAddress, port);
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//实例化一个套接字对象
            try
            {
                ricServerMess.Text += "开始连接服务器:" + txtIP.Text.Trim() + ":" + txtPort.Text.Trim() + "\n";
                socketClient.Connect(endPoint);//连接到指定的终结点
                ricServerMess.Text += "连接成功!正在等待服务器回复!......\n";
                if (!thread.IsAlive)
                {
                    thread.Start();
                }
                isAlive = true;
                btnLink.Enabled = false;
                btnClose.Enabled = true;
            }
            catch (Exception ex)
            {
                ricServerMess.Text += "没有找到可供连接的远程服务,请联系管理员!\n";
            }
        }
        /// <summary>
        /// 用于接收服务器回复的信息并处理
        /// </summary>
        private void ReceiveMessage()
        {
            byte[] buffer = new byte[1024 * 1024 * 1024];//实例化一个接收数据的缓冲区
            while (true)//用于循环接收
            {
                if (!isAlive)
                {
                    Thread.Sleep(50);
                    continue;
                }
                try
                {
                    if (socketClient.Connected)
                    {
                        int length = socketClient.Receive(buffer);//接收数据并存放到缓冲区内
                        string str = Encoding.UTF8.GetString(buffer, 0, length);//将信息转换成数据
                        if (string.IsNullOrEmpty(str))
                        {
                            continue;
                        }
                        if (ricClientMessage.InvokeRequired)
                        {
                            ricClientMessage.Invoke(new Action(() =>
                            {
                                ricClientMessage.Text += str;
                            }));
                        }
                    }
                    else
                    {
                        isAlive = false;
                        if (ricClientMessage.InvokeRequired)
                        {
                            ricClientMessage.Invoke(new Action(() =>
                            {
                                ricServerMess.Text += "已断开与远程服务器的连接!\n";
                            }));
                        }
                    }
                    Thread.Sleep(20);
                }
                catch (Exception)
                {
                }
            }
        }

        private void ricMessage_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (string.IsNullOrEmpty(ricMessage.Text.Trim()))
                {
                    return;
                }
                byte[] buffer= Encoding.UTF8.GetBytes(ricMessage.Text);
                if (socketClient.Connected)
                {
                    socketClient.Send(buffer);
                    ricMessage.Text = "";
                }
                else
                {
                    ricServerMess.Text += "已断开与远程服务器的连接!\n";
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            socketClient.Close();
            isAlive = false;
            btnLink.Enabled = true;
            btnClose.Enabled = false;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            thread = new Thread(ReceiveMessage);
            thread.IsBackground = true;//设置线程为后台线程
        }
    }
}
